package com.ot.flink.cdc.biz.service.impl;

import com.ot.flink.cdc.biz.domain.CdcTask;
import com.ot.flink.cdc.biz.service.TaskService;
import com.ot.flink.cdc.common.TaskStatusEnum;
import com.ot.flink.cdc.function.CdcHolder;
import com.ot.flink.cdc.function.CdcRunner;
import com.ot.flink.cdc.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author: admin
 * @date: 2024/5/24
 * @since JDK1.8 version: 1.0.0
 */
@Service
public class TaskServiceImpl implements TaskService {

    @Resource
    private CdcHolder cdcHolder;

    @Override
    public void addTask(CdcTask taskInfo) {
    }

    @Override
    public void stopOrStartTask(CdcTask params) {
        CdcTask task = CdcHolder.tasks.get(params.getName());
        if (null != task) {
            if (TaskStatusEnum.RUNNING.getCode().equals(params.getStatus())) {
                try {
                    task.getJobClient().cancel().get();
                    task.setStatus(TaskStatusEnum.STOP.getCode());
                    task.setStatusDesc(TaskStatusEnum.STOP.getDesc());
                } catch (Exception e) {
                    task.setStatus(TaskStatusEnum.STOP_ERROR.getCode());
                    task.setStatusDesc(TaskStatusEnum.STOP_ERROR.getDesc());
                    task.setMark(e.getMessage());
                    throw new RuntimeException(e);
                }
            } else {
                cdcHolder.start();
            }
        }
    }

    @Override
    public CdcTask getTask(final String name) {
        return CdcHolder.tasks.get(name);
    }

    @Override
    public List<CdcTask> getAllTask() {
        return new ArrayList<>(CdcHolder.tasks.values());
    }

}
